class IdentitiesController < ApplicationController
  
  helper :profiles
  
  auto_complete_for :site, :name, :order => 'approved DESC' # 'false' is before 'true' in alphabetic order
  
  before_filter :check_authentication, :except => [ :guest_view, :search ]
  
  ALL_SITES = -1
  
  def guest_view
    find_user_and_render_public_page
  end
  
  def search
    @sites = Site.find(:all)
    if request.post? && !params[:webid].blank?
      if params[:sites].to_i == ALL_SITES
        conditions = ["name like ?", '%' + params[:webid] + '%'] 
      else
        conditions = ["name like ? and site_id = ?", '%' + params[:webid] + '%', params[:sites]] 
      end
      @results = Identity.find(:all, :conditions => conditions)
    end
  end
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
  :redirect_to => { :action => :list }
  
  def list
    @identities = Identity.find :all, :conditions => ["user_id = #{session[:user]}"]
  end
  
  def show
    @identity = Identity.find(params[:id])
  end
  
  def new
    @identity = Identity.new
    @identity.public = true
    @identity.site = Site.find(params[:site_id]) if params[:site_id]
  end
  
  def create
    @identity = Identity.new(params[:identity])
    
    site = Site.find_by_name params[:site][:name]
    unless site
      flash[:notice] = 'Site not exist, do you wanna create it now?'
      redirect_to :controller => "sites", :action => "new", :site_name => params[:site][:name]
      return
    end
    @identity.site = site
    
    @identity.user_id = session[:user]
    if @identity.save
      flash[:notice] = 'Identity was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end
  
  def edit
    @identity = @user.fetch_identity(params[:id])    
  end
  
  def update
    @identity = @user.fetch_identity(params[:id])    
    if @identity.update_attributes(params[:identity])
      flash[:notice] = 'Identity was successfully updated.'
      redirect_to :action => 'list'
    else
      render :action => 'edit'
    end
  end
  
  def destroy
    @identity = @user.fetch_identity(params[:id])    
    Identity.destroy(params[:id])
    redirect_to :action => 'list'
  end
  
end
